package p.sunmes.les.actor;

import java.util.HashMap;
import java.util.Map;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.utils.Align;

public class PicString extends Group {

	private Map<Character, Actor> dict = new HashMap<Character, Actor>();

	private int alignment = Align.bottomLeft;
	private String text = "";
	private float xOff = 0;

	public PicString() {

	}

	public float getXOff() {
		return xOff;
	}

	public void setXOff(float off) {
		xOff = off;
		updatePics();
	}

	@Override
	public void setColor(Color color) {
		super.setColor(color);
		for (Actor a : getChildren()) {
			a.setColor(color);
		}
	}

	public void updatePics() {
		float x = getX();
		float y = getY();
		float wd = getWidth();
		float hg = getHeight();

		groupCharPics();

		switch (alignment) {
		case Align.bottomLeft:
			break;
		case Align.bottom:
			setPosition(x + wd / 2, y, Align.bottom);
			break;
		case Align.bottomRight:
			setPosition(x + wd, y, Align.bottomRight);
			break;
		case Align.center:
			setPosition(x + wd / 2, y + hg / 2, Align.center);
			break;
		case Align.left:
			setPosition(x, y + hg / 2, Align.left);
			break;
		case Align.right:
			setPosition(x + wd, y + hg / 2, Align.right);
			break;
		case Align.topLeft:
			setPosition(x, y + hg, Align.topLeft);
			break;
		case Align.top:
			setPosition(x + wd / 2, y + hg, Align.top);
			break;
		case Align.topRight:
			setPosition(x + wd, y + hg, Align.topRight);
			break;
		default:
			break;
		}
	}

	private void groupCharPics() {
		clearChildren();
		float x = 0, h = 0;
		for (int i = 0; i < text.length(); i++) {
			char c = text.charAt(i);
			Actor a = dict.get(c);
			if (a != null) {
				addActor(a);
				a.setPosition(x, 0);
				x += a.getWidth() + xOff;
				if (h < a.getHeight()) {
					h = a.getHeight();
				}
			}
		}
		if (x > 0) {
			x -= xOff;
		}
		setWidth(x);
		setHeight(h);
	}

	public void setText(String text) {
		this.text = text;
		updatePics();
	}

	public void setAlignment(int align) {
		alignment = align;
		updatePics();
	}

	public void addPicCharacter(char c, Actor pic) {
		dict.put(c, pic);
		updatePics();
	}

}
